package com.example.controller;

import com.example.service.AsyncService;
import com.example.service.RequestAttrService;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 异步测试入口
 */
@RestController
public class AsyncController {

	@Resource
	private AsyncService asyncService;

	@Resource
	private RequestAttrService requestAttrService;

	@PostMapping("/testAsync")
	public String testAsync() throws ExecutionException, InterruptedException {
		// 返回值为Future
		Future<String> future = asyncService.asyncFuture();
		System.out.println(future.get());

		// 返回值为CompletableFuture
		CompletableFuture<String> completableFuture = asyncService.asyncCompletableFuture();
		System.out.println(completableFuture.join());

		// 返回ListenableFuture
		ListenableFuture<String> listenableFuture = asyncService.asyncListenableFuture();
		listenableFuture.addCallback((result)->{
			System.out.println("执行成功，结果："+result);
		},(e)->{
			System.out.println("执行失败,异常："+e.getMessage());
		});

		// 没有返回值后者返回其它
		asyncService.asyncWithoutResult();

		return "success";
	}

	@PostMapping("/testAsyncFutureWithCompletableFuture")
	public String testAsyncFutureWithCompletableFuture() {
		CompletableFuture<String> completableFuture = asyncService.asyncCompletableFuture();
		return completableFuture.join();
	}

	@GetMapping("/testGetRequestAttr")
	public String testGetRequestAttr() throws Exception {
		return requestAttrService.getRequestAttr();
	}


}
